package com.fingard.dsp.bank.directbank.vbao01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.vbao.service.trade.VbaoChargeSystemHandler;
import com.vbao.service.trade.bean.request.SingleDFRequest;
import com.vbao.service.trade.bean.request.SingleQueryRequest;
import com.vbao.service.trade.bean.request.TradeRequestXml;
import com.vbao.service.trade.utils.TradeCodeEnum;


public class VBAO01SinglePay extends VBAO01Base implements ISinglePay {
	public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
		RetAtsSglDetail retDetail = new RetAtsSglDetail();

		ActSetItem actItem = getBankConfig().getActSetItem(p_req1908.singleDetail.payAct, "");
		if (actItem == null) {
			retDetail.respCode = "0";
			retDetail.respInfo = "未找到账号:[" + p_req1908.singleDetail.payAct + "]对应的商户配置信息";
			retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
			retDetail.transState = PaymentState.FAIL_Payment;
			retDetail.payInfoCode = FailCode.E9981;
			retAts.writeRetDetail(retDetail);
			return retAts;
		}

		SingleDFRequest singlePayRequest = new SingleDFRequest();

		singlePayRequest.setVersion("6.0");
		singlePayRequest.setInputCharset(getCharset());
		singlePayRequest.setSignType("MD5");
		singlePayRequest.setCustomerNo(actItem.merchantId);
		
		String goodNo = "";
		boolean useEachGoodNo = getBankConfig().getValueAsBool("isUseEachGoodNo");
		if (useEachGoodNo) {
			goodNo = actItem.goodNo;
		} else {
			goodNo = getBankConfig().getValueAsString("GoodNo");
		}
		if (StringHelper.isNullOrEmpty(goodNo)) {
			WriteBankLogLn("配置文件缺失'GoodNo'配置!");
		}
		
		singlePayRequest.setGoodNo(goodNo);
		singlePayRequest.setActName(p_req1908.singleDetail.payName);
		singlePayRequest.setActId(p_req1908.singleDetail.payAct);
		singlePayRequest.setActLineCode(p_req1908.singleDetail.cnapsCode);
		singlePayRequest.setOrderNo(p_req1908.singleDetail.askNumber);
		singlePayRequest.setOrderAmount(p_req1908.singleDetail.payAmount);

		// 1 折 2 借记卡 3 贷记卡 4 准贷记卡
		String cardType = p_req1908.singleDetail.cardType;
		if (cardType.equals("3") || cardType.equals("4")) {
			singlePayRequest.setBankCardType("2");// 信用卡
			singlePayRequest.setCertType(convertCertTypeToBank(p_req1908.singleDetail.certType));
			singlePayRequest.setCertId(p_req1908.singleDetail.certNum);
			singlePayRequest.setMobile(p_req1908.singleDetail.cellPhone);
			singlePayRequest.setCreditValid(p_req1908.singleDetail.expiredDate);
			singlePayRequest.setCreditCvv2(p_req1908.singleDetail.cvv2);
		} else if (cardType.equals("1")) {
			singlePayRequest.setBankCardType("1");//折
		} else {
			singlePayRequest.setBankCardType("0");// 卡
		}

		String bankCode = p_req1908.singleDetail.recBankCode;
		singlePayRequest.setBankCode(getBankConfig().getMapValueByKey("BankCodeMapping", bankCode));

		singlePayRequest.setBankCardNo(p_req1908.singleDetail.recAct);
		singlePayRequest.setBankCardName(p_req1908.singleDetail.recName);
		singlePayRequest.setProductName(p_req1908.singleDetail.askNumber);

		VbaoChargeSystemHandler vbaoChargeSystemHandler = new VbaoChargeSystemHandler();
		TradeRequestXml tradeRequestXml = vbaoChargeSystemHandler.creatRequestXml(singlePayRequest,actItem.saltKey,getCharset(),TradeCodeEnum.SINGLE_DF.getCode());

		WriteBankLogLn2("发送报文明文:" + tradeRequestXml.getOriRequestXml());
		WriteBankLogStep2(tradeRequestXml.getRequestXml());

		if(tradeRequestXml.getErrMsg() == null) {
			String reqURL = bankFront.getUrl("1908");
			WriteBankLogLn2("微保实时付款提交服务地址: " + reqURL);

			// 发送银行并获取返回
			String returnDFPayxml = vbaoChargeSystemHandler.http(reqURL,tradeRequestXml.getRequestXml(),getCharset());

			WriteBankLogLn2("微保返回报文密文:\r\n" + returnDFPayxml);

			if(returnDFPayxml != null) {
				try {
					String returnOriDFPayxml = Base64vbao.decode(returnDFPayxml, getCharset());
					//returnOriDFPayxml = new String(returnOriDFPayxml.getBytes(),getCharset());

					WriteBankLogStep3(returnOriDFPayxml);

					StringBuilder tmpSbMsg = new StringBuilder();
					XmlTextReader tmpBkReader = loadBankRespXmlReader(returnOriDFPayxml, tmpSbMsg);

					if (tmpBkReader != null) {
						retDetail.respCode = "0";
						retDetail.respInfo = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");

						String tmpReturnCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ResultCode");
						if (tmpReturnCode.equals("T")) {
							retDetail.transAmt = tmpBkReader.getFirstText("/TResponse/OrderInfo/OrderAmount");
							retDetail.transState = tmpReturnCode + "+" + tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode") + "+" + tmpBkReader.getFirstText("/TResponse/OrderInfo/PayStatus");
							retDetail.payInfoCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
							retDetail.reqSeqID = tmpBkReader.getFirstText("/TResponse/OrderInfo/OrderNo");
						} else {
							String errorCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
							retDetail.transState = tmpReturnCode + "+" + errorCode;
							retDetail.payInfoCode = errorCode;
							retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
						}
					} else {
						retDetail.respCode = "-1";
						retDetail.respInfo = tmpSbMsg.toString();
					}
				} catch (Exception e) {
					retDetail.respCode = "-1";
					retDetail.respInfo = e.getMessage();
					e.printStackTrace();
				}
			}
		} else {
			retDetail.respCode = "-1";
			retDetail.respInfo = tradeRequestXml.getErrMsg();
		}

		if (retDetail.respCode.equals("-1")	&& StringHelper.isNullOrEmpty(retDetail.reqSeqID)) {
			retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
		}

		retAts.writeRetDetail(retDetail);
		return retAts;

	}

	@Override
	public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
		return null;
	}

	public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception{
		RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
		RetAtsSglDetail retDetail = new RetAtsSglDetail();

		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_req1944.payAct, "");
			if (actItem == null) {
				retDetail.respCode = "-1";
				retDetail.respInfo = "未找到账号:[" + p_req1944.payAct + "]商户配置信息";
				retAts.writeRetDetail(retDetail);
				return retAts;
			}
		
			SingleQueryRequest singleQueryRequest = new SingleQueryRequest();
			singleQueryRequest.setVersion("6.0");
			singleQueryRequest.setInputCharset(getCharset());
			singleQueryRequest.setSignType("MD5");
			singleQueryRequest.setCustomerNo(actItem.merchantId);
			singleQueryRequest.setPayDate(Format.Date8Format.format(p_req1944.getBgnDateTime()));
			singleQueryRequest.setOrderNo(p_req1944.askNumber);

			VbaoChargeSystemHandler vbaoChargeSystemHandler = new VbaoChargeSystemHandler();
			TradeRequestXml tradeRequestXml = vbaoChargeSystemHandler.creatRequestXml(singleQueryRequest, actItem.saltKey, getCharset(), TradeCodeEnum.SINGLE_QUERY.getCode());

			WriteBankLogLn2("发送微保请求报文明文:"+tradeRequestXml.getOriRequestXml());
			WriteBankLogStep2(tradeRequestXml.getRequestXml());

			if (tradeRequestXml.getErrMsg() == null) {
				String postURL = bankFront.getUrl("1944");
				WriteBankLogLn2("微保实时付款状态查询服务地址: " + postURL);

				String returnDFPayxml = vbaoChargeSystemHandler.http(postURL, tradeRequestXml.getRequestXml(), getCharset());

				WriteBankLogLn2("微保返回报文密文:\r\n" + returnDFPayxml);

				if (returnDFPayxml != null){
					String returnOriDFPayxml = Base64vbao.decode(returnDFPayxml, getCharset());
					//returnOriDFPayxml = new String(returnOriDFPayxml.getBytes(),getCharset());

					WriteBankLogStep3(returnOriDFPayxml);

					StringBuilder tmpSbMsg = new StringBuilder();
					XmlTextReader tmpBkReader = loadBankRespXmlReader(returnOriDFPayxml, tmpSbMsg);

					if (tmpBkReader != null) {
						retDetail.respCode = "0";
						retDetail.respInfo = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");
						retDetail.reqSeqID = tmpBkReader.getFirstText("/TResponse/OrderInfo/OrderNo");

						String tmpReturnCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ResultCode");
						if (tmpReturnCode.equals("T")) {
							retDetail.transAmt = tmpBkReader.getFirstText("/TResponse/OrderInfo/OrderAmount");
							retDetail.transState = tmpReturnCode + "+" + tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode") + "+" + tmpBkReader.getFirstText("/TResponse/OrderInfo/PayStatus");
							retDetail.payInfoCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
						} else {
							if(StringHelper.isNullOrEmpty(retDetail.reqSeqID)){
								retDetail.reqSeqID = p_req1944.askNumber;
							}
							String bkErrCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
							String bkDescription = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");
							boolean chked = true;
							if("A2001".equals(bkErrCode) || (bkDescription!=null && bkDescription.contains("交易记录不存在"))){
								chked = canBeNotExist(p_req1944, retDetail, 20);
							}
							if(chked){
								retDetail.transState = tmpReturnCode + "+" + bkErrCode + "+" + bkDescription;
								retDetail.payInfoCode = bkErrCode;
							}
						}
					} else {
						retDetail.respCode = "-1";
						retDetail.respInfo = tmpSbMsg.toString();
					}
				}
			} else {
				retDetail.respCode = "-1";
				retDetail.respInfo = tradeRequestXml.getErrMsg();
			}
		} catch (Exception e) {
			retDetail.respCode = "-1";
			retDetail.respInfo = e.getMessage();
			e.printStackTrace();
		}

		if (retDetail.respCode.equals("-1")	&& StringHelper.isNullOrEmpty(retDetail.reqSeqID)) {
			retDetail.reqSeqID = p_req1944.askNumber;
		}

		retAts.writeRetDetail(retDetail);
		return retAts;
	}

	@Override
	public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
		return null;
	}
}
